package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.com.elite.Util
/**
 * 工单查询API
 */

public class apiWoContact implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoContact.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            //解析Json
            JSONObject inJson = JSONObject.parseObject(callJson);

            //获取页面信息参数
            String in_s_objetive_guid = inJson.getJSONObject("data").getString("in_s_objetive_guid"); //当前objective_guid
            String in_r_map_id = inJson.getJSONObject("data").getString("in_r_map_id"); //当前mapid

            String staff_role_id = "";
            String in_objectivesubstatus = "SENDCU";

            log.debug("in_s_objetive_guid:" + in_s_objetive_guid);
            log.debug("in_r_map_id:" + in_r_map_id);
            //关联工单处理逻辑
            String queryWorkOrderSQL = "select uuid() as task_guid,operation_type,now() as modifiddate,UUID() as objective_guid,objectivetype_id,concat('GL',DATE_FORMAT(now(),'%Y%m%d%H%i%s')) as workorder_id,map_id as send_map,node_id as send_node,rolegroup_id as send_group,case when staff_id is null then '' else staff_id end as send_staff " +
            "from c_codetables where use_status = '0' and use_type='WO_CONTACT' and code_id = '" + in_r_map_id + "'";

            log.debug("执行任务数据查询SQL:" + queryWorkOrderSQL);
            List WorkOrderList = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");
            //获取总行数
            log.debug("执行工单查询数据SQL获取总条数:" + WorkOrderList.size());

            for (int i = 0; i < WorkOrderList.size(); i++) {

                Map selectResultcm = WorkOrderList.get(i);
                String task_map_id = selectResultcm.get("send_map");
                String task_nod_id = selectResultcm.get("send_node");
                String task_group_id = selectResultcm.get("send_group");
                String task_staff_id = selectResultcm.get("send_staff");
                String task_modifiddate = selectResultcm.get("modifiddate");
                String task_objective_guid = selectResultcm.get("objective_guid");
                String task_workorder_id = selectResultcm.get("workorder_id");
                String task_guid = selectResultcm.get("task_guid");

                log.debug("task_modifiddate:" + task_modifiddate);
                log.debug("下送节点:" + task_map_id);
                log.debug("下送节点:" + task_nod_id);
                log.debug("下送组别:" + task_group_id);
                log.debug("下送人:" + task_staff_id);
                log.debug("task_objective_guid:" + task_objective_guid);
                log.debug("task_workorder_id:" + task_workorder_id);

                //查询当前处理人的角色
                String queryStaffRoleSQL = "select role_id from staffrole where staff_id = '" + task_staff_id + "' limit 1  ";
                log.debug("执行坐席角色数据查询SQL:" + queryStaffRoleSQL);
                List queryStaffRoleList = eliteBean.chaxun_sql(queryStaffRoleSQL, "dataSource");
                log.debug("执行工单查询数据SQL获取总条数:" + queryStaffRoleList.size());
                if (queryStaffRoleList.size()>0)
                {
                    staff_role_id = queryStaffRoleList.get(0).get("role_id");
                    log.debug("staff_role_id:" + staff_role_id);
                }else
                {
                    staff_role_id = "ZCJZVW";
                }

                String[] data = new String[6];
                log.debug("***************************");
                //插入步骤信息表
                data[0]  = "insert into workorderstep3(workorderstep_guid,workorder_guid,oldhandleby_id,oldhandlegroup_id,handleby_id,handlegroup_id,workorderstepstatus,comments," +
                        "modifieddate,from_stepidmap,to_stepidmap,stepexpired,stepstart,cur_expiredlen,cur_expiredflag,workstarttime,workendtime) " +
                        "values (uuid(), '" + task_objective_guid + "','" + task_staff_id + "','" + task_group_id + "','" + task_staff_id + "','" + task_group_id + "','SENDNS',null,'" +
                        task_modifiddate + "','" + task_nod_id + "','" + task_nod_id + "','" + task_modifiddate + "','" + task_modifiddate + "','0','0','" + task_modifiddate + "','" + task_modifiddate + "')";
                //插入工单路径数据
                data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                        "values (uuid(), '" + task_objective_guid + "','" + task_group_id + "','" + task_staff_id + "','" + task_modifiddate + "','" + task_map_id + "','" + task_nod_id + "','" + task_nod_id+"')";
                //插入objective
                data[2] = "insert into objective (objective_guid,objectivetype_id,handleby_id,handlegroup_id,priority_id,customer_guid,expireddate,objectivestatus,comments,createdby,\n" +
                        "createddate,modifiedby,modifieddate,workorderframe_id,workorderid,flowdetail,objectivesubstatus,map_id,curstep_id_map,gl_objective_guid)\n" +
                        "select '" + task_objective_guid + "',objectivetype_id,'" + task_staff_id + "','" + task_group_id + "', priority_id,customer_guid,expireddate,'OPEN',null,createdby,\n" +
                        "       createddate,modifiedby,modifieddate,'" + task_map_id + "','" + task_workorder_id + "',null,'SENDCU','" + task_map_id + "','" + task_nod_id + "',objective_guid \n" +
                        "  from objective where objective_guid = '" + in_s_objetive_guid + "'";
                //插入elitetask
                data[3] = "insert into elitetask (elitetask_guid,objective_guid,objectivetype_id,expectstarttime,expectendtime,priority,handleby_id,handlegroup_id,createdby,createddate,\n" +
                        "modifiedby,modifieddate,currentexpectstarttime,comments,customer_guid,curstepstatus,curstep_id,curstep_id_map,map_id,objectivesubstatus,obflag,cur_roleid,auto_sendto) \n" +
                        "select '" + task_guid + "','" + task_objective_guid + "',t1.objectivetype_id,t1.expectstarttime,t1.expectendtime,'NORMAL','" + task_staff_id + "','" + task_group_id + "',t1.createdby,t1.createddate,\n" +
                        "       t1.modifiedby,t1.modifieddate,now(),null,t1.customer_guid,'OPEN','" + task_nod_id + "','" + task_nod_id + "','" + task_map_id +"','SENDCU','0','" + staff_role_id + "',t2.auto_sendto\n" +
                        "  from objective t1 left join elitetask t2 on t1.objective_guid = t2.objective_guid where t1.objective_guid = '" + in_s_objetive_guid + "'";
                //插入tabc表数据
                data[4]  = "insert into tabcwo_business_info(relation_id,customer_guid,operation_type,lease_term_end,workorder_type,workorder_id,print_flag,oldworkerorderguid,acceptor,writedate,business_type,contract_title,stalls_code,lease_term,operating_area,area,contract_content,stalls_subtotal,handling_department,batch_operating_area,undertaker,handledby,undertaker_mobile,tenant_address,tenant,tenant_hometown,tenant_mobile,tenant_code,inside_outside,stalls_orarea_decoration,retreat_deposit_type,builder,construction_unit,construction_time,fire,valid_documents,identity_number,coast_water_deposit,coast_electricity_deposit,earnest_money, deposit_summary,deposit_amount,toll_standard, renamed_money,monthly_rent,monthly_management_fee,water_fee,electricity_bill,lease_deposit, summary_payment,decoration_deposit,electricity_service_charge,driving_license_number,driving_license_name,vehicle_model,carno,driver_license_number,driver_license_name,old_contract,old_tenant,wo_type,wo_description,urgent_level,expectendtime,repair_fee,repair_aera_type,repair_flag,retreat_deposit_reason,acceptorname,roback_flag)\n" +
                        "select '" + task_objective_guid + "',customer_guid,operation_type,lease_term_end,workorder_type,workorder_id,print_flag,oldworkerorderguid,acceptor,writedate,business_type,contract_title,stalls_code,lease_term,operating_area,area,contract_content,stalls_subtotal,handling_department,batch_operating_area,undertaker,handledby,undertaker_mobile,tenant_address,tenant,tenant_hometown,tenant_mobile,tenant_code,inside_outside,stalls_orarea_decoration,retreat_deposit_type,builder,construction_unit,construction_time,fire,valid_documents,identity_number,coast_water_deposit,coast_electricity_deposit,earnest_money, deposit_summary,deposit_amount,toll_standard, renamed_money,monthly_rent,monthly_management_fee,water_fee,electricity_bill,lease_deposit, summary_payment,decoration_deposit,electricity_service_charge,driving_license_number,driving_license_name,vehicle_model,carno,driver_license_number,driver_license_name,old_contract,old_tenant,wo_type,wo_description,urgent_level,expectendtime,repair_fee,repair_aera_type,repair_flag,retreat_deposit_reason,acceptorname,roback_flag\n" +
                        "  from tabcwo_business_info \n" +
                        " where relation_id = '" + in_s_objetive_guid + "'";
                //插入tabchis表
                data[5]  = "insert into tabcwo_business_info_his(hisguid,relation_id,customer_guid,operation_type,lease_term_end,workorder_type,workorder_id,print_flag,oldworkerorderguid,acceptor,writedate,business_type,contract_title,stalls_code,lease_term,operating_area,area,contract_content,stalls_subtotal,handling_department,batch_operating_area,undertaker,handledby,undertaker_mobile,tenant_address,tenant,tenant_hometown,tenant_mobile,tenant_code,inside_outside,stalls_orarea_decoration,retreat_deposit_type,builder,construction_unit,construction_time,fire,valid_documents,identity_number,coast_water_deposit,coast_electricity_deposit,earnest_money, deposit_summary,deposit_amount,toll_standard, renamed_money,monthly_rent,monthly_management_fee,water_fee,electricity_bill,lease_deposit, summary_payment,decoration_deposit,electricity_service_charge,driving_license_number,driving_license_name,vehicle_model,carno,driver_license_number,driver_license_name,old_contract,old_tenant,wo_type,wo_description,urgent_level,expectendtime,repair_fee,repair_aera_type,repair_flag,retreat_deposit_reason,acceptorname,roback_flag)\n" +
                        "select uuid(),'"+ task_objective_guid + "',customer_guid,operation_type,lease_term_end,workorder_type,workorder_id,print_flag,oldworkerorderguid,acceptor,writedate,business_type,contract_title,stalls_code,lease_term,operating_area,area,contract_content,stalls_subtotal,handling_department,batch_operating_area,undertaker,handledby,undertaker_mobile,tenant_address,tenant,tenant_hometown,tenant_mobile,tenant_code,inside_outside,stalls_orarea_decoration,retreat_deposit_type,builder,construction_unit,construction_time,fire,valid_documents,identity_number,coast_water_deposit,coast_electricity_deposit,earnest_money, deposit_summary,deposit_amount,toll_standard, renamed_money,monthly_rent,monthly_management_fee,water_fee,electricity_bill,lease_deposit, summary_payment,decoration_deposit,electricity_service_charge,driving_license_number,driving_license_name,vehicle_model,carno,driver_license_number,driver_license_name,old_contract,old_tenant,wo_type,wo_description,urgent_level,expectendtime,repair_fee,repair_aera_type,repair_flag,retreat_deposit_reason,acceptorname,roback_flag\n" +
                        "  from tabcwo_business_info \n" +
                        " where relation_id = '" + in_s_objetive_guid + "'";
                log.debug("当前执行更新结果SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, 'dataSource');
                log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

                //调用短信发送接口发送短信
                String post_body = '''{"data":{"in_r_objectivesubstatus":"''' + in_objectivesubstatus + '''",''' +
                        '''"in_map_roleid":"''' + staff_role_id + '''",''' +
                        '''"in_r_remark":"",''' +
                        '''"in_s_objetive_guid":"''' + task_objective_guid + '''",''' +
                        '''"in_s_elitetask_guid":"''' + task_guid + '''",''' +
                        '''"in_r_map_id":"''' + task_map_id + '''",''' +
                        '''"in_r_node_id":"''' + task_nod_id + '''"}}'''

                String woMessageURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWoMessageEntrance";
                String woMessageResult = Util.doHttpPost(woMessageURL, post_body, "UTF-8", 5000, 0);
                JSONObject woMessageJson = JSONObject.parseObject(woMessageResult);
                String re_code = woMessageJson.getString("code");
            }

            long endTime = System.currentTimeMillis();
            result.put("code", 1);
            result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        }

        return result.toString();

    }
}